/**
 * 数据库配置文件
 * PC微信聊天应用 - MySQL数据库配置
 */

const mysql = require('mysql2/promise');

// 数据库连接配置
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '0519',
  database: process.env.DB_NAME || 'pc_wechat_chat',
  charset: 'utf8mb4',
  timezone: '+08:00',
  // 连接池配置
  connectionLimit: 10,
  queueLimit: 0
};

// 创建连接池
const pool = mysql.createPool(dbConfig);

/**
 * 数据库连接类
 */
class Database {
  constructor() {
    this.pool = pool;
  }

  /**
   * 执行查询
   * @param {string} sql SQL语句
   * @param {Array} params 参数
   * @returns {Promise} 查询结果
   */
  async query(sql, params = []) {
    try {
      const [rows] = await this.pool.execute(sql, params);
      return rows;
    } catch (error) {
      console.error('数据库查询错误:', error);
      throw error;
    }
  }

  /**
   * 执行事务
   * @param {Function} callback 事务回调函数
   * @returns {Promise} 事务结果
   */
  async transaction(callback) {
    const connection = await this.pool.getConnection();
    try {
      await connection.beginTransaction();
      const result = await callback(connection);
      await connection.commit();
      return result;
    } catch (error) {
      await connection.rollback();
      console.error('事务执行错误:', error);
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 测试数据库连接
   * @returns {Promise<boolean>} 连接状态
   */
  async testConnection() {
    try {
      const [rows] = await this.pool.execute('SELECT 1 as test');
      console.log('✅ 数据库连接成功');
      return true;
    } catch (error) {
      console.error('❌ 数据库连接失败:', error.message);
      return false;
    }
  }

  /**
   * 关闭连接池
   */
  async close() {
    try {
      await this.pool.end();
      console.log('数据库连接池已关闭');
    } catch (error) {
      console.error('关闭数据库连接池错误:', error);
    }
  }

  /**
   * 获取连接池状态
   * @returns {Object} 连接池状态信息
   */
  getPoolStatus() {
    return {
      totalConnections: this.pool._allConnections.length,
      freeConnections: this.pool._freeConnections.length,
      acquiringConnections: this.pool._acquiringConnections.length,
      queuedConnections: this.pool._connectionQueue.length
    };
  }
}

// 创建数据库实例
const db = new Database();

// 导出数据库实例和配置
module.exports = {
  db,
  dbConfig,
  pool
};

// 进程退出时关闭数据库连接
process.on('SIGINT', async () => {
  console.log('正在关闭数据库连接...');
  await db.close();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  console.log('正在关闭数据库连接...');
  await db.close();
  process.exit(0);
});
